<?php
/*
 * @Author: 孙开源 && sunkaiyuan@namenode.cn
 * @Date: 2023-04-12 16:45:39
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @LastEditTime: 2023-04-18 15:12:03
 * @Description: 
 * 
 */

namespace zhijingfeisuo\Kernel\Services;

use Monolog\Logger as MonoLoger;
use Monolog\Handler\StreamHandler;

class Logger
    {

    /**
     * @var \zhijingfeisuo\Application
     */
    protected $app;
    /**
     * cache 驱动
     * @var Monolog\Logger
     */
    protected $loggerDriver;
    /**
     * Logger constructor.
     *
     * @param \zhijingfeisuo\Application
     */
    public function __construct($app)
        {
        $this->app = $app;
        }


    public function __call($name, $a)
        {
        if ($this->app->config['log']['enable']) {
            if ($this->loggerDriver == null)
                $this->loggerDriver = $this->getLogger();
            return $this->loggerDriver->$name(...$a);
            }
        }

    /**
     * @return Monolog\Logger
     */
    public function getLogger()
        {
        if ($this->loggerDriver) {
            return $this->loggerDriver;
            }

        if (property_exists($this, 'logger') && $this->app->offsetExists('logger') && ($this->app['logger'] instanceof Logger)) {
            return $this->loggerDriver = $this->app['logger'];
            }

        return $this->loggerDriver = $this->createDefaultLog();
        }

    public function setLogger($logger)
        {
        $this->loggerDriver = $logger;
        }
    /**
     * @return Monolog\Logger
     */
    protected function createDefaultLog()
        {
        return new MonoLoger(
            'zhijingfeisuo',
            [
                new StreamHandler(
                    isset($this->app->config['log']['path']) ? $this->app->config['log']['path'] : sys_get_temp_dir() . '/zhijingfeisuo.log',
                    isset($this->app->config['log']['level']) ? $this->app->config['log']['level'] : 'debug'
                )
            ]
        );
        }
    }